import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Select,
  Button,
  Table,
  Divider,
  Modal,
  Badge,
  Tooltip,
} from 'antd';

import { TableListData } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
const { pathname } = window.location;

const statusMap = ['default', 'success'];
const statusText = ['无效', '有效'];

interface CooperationListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: TableListData;
  INITINFO: any;
  screen: string;
  hasPath: string;
}

interface CooperationListState {
  searchValues: any;
  typeVisible: boolean;
  pageIndex:number;
  pageSize:number;
  rowId:number;
  changeType: {
    id: number;
    status: number;
  };
}

@connect(
  ({
    cooperationCompanyList: { dataInfo },
    common: { INITINFO },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    INITINFO,
    screen,
    hasPath,
    loading: loading.effects['cooperationCompanyList/fetch'],
  }),
)
class CooperationListInfoElem extends React.Component<CooperationListProps, CooperationListState> {
  columns = [
    {
      title: '快递公司',
      dataIndex: 'pcName',
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowCooperation(record.id)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '类型',
      dataIndex: 'typeName',
    },
    {
      title: '物流中心/小区',
      dataIndex: 'logisName',
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '对接状态',
      dataIndex: 'status',
      render: (val: string) => <Badge status={statusMap[val]} text={statusText[val]} />,
    },
    {
      title: '第三方审核状态',
      dataIndex: 'auditStateName',
    },
    {
      title: '操作',
      width: 200,
      render: (val: any, record: any) => (
        <>
          <span className="operLink" onClick={() => this.handleEditCooperation(record.id)}>
            编辑
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleShowCooperation(record.id)}>
            详情
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleChangeTypeModal(true, record)}>
            设为{record.status ? '无效' : '有效'}
          </span>
        </>
      ),
    },
  ];

  state: CooperationListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
    typeVisible: false,
    changeType: {
      id: 0,
      status: 0,
    },
  };

  static getDerivedStateFromProps(nextProps: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchPartner');
    this.fetchAction('common/fetchLogisList');
    this.fetchAction('common/fetchGardenList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  /**
   * 新建站点
   */
  handleAddCooperation = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建站点',
      url: '/basic/cooperationCompany/list/add',
    });
  };

  /**
   * 批量添加站点
   */
  handleBatchAddCooperation = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '批量添加',
      url: '/basic/cooperationCompany/list/batchAdd',
    });
  };

  /**
   * 编辑站点
   */
  handleEditCooperation = (id: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '编辑站点',
      url: `/basic/cooperationCompany/list/edit?id=${id}`,
    });
  };

  /**
   * 查看站点
   */
  handleShowCooperation = (id: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '查看站点',
      url: `/basic/cooperationCompany/list/detail?id=${id}`,
    });
  };

  handleChangeTypeModal = (typeVisible: boolean, record?: any) => {
    this.setState({
      typeVisible,
      changeType: {
        id: record ? record.id : 0,
        status: record && record.status === 1 ? 0 : 1,
      },
    });
  };

  handleChangeType = () => {
    const { searchValues: search, changeType } = this.state;
    const params = { search, ...changeType };
    this.fetchAction('changeType', params);
    this.handleChangeTypeModal(false);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '数据对接配置',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '数据对接配置',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '数据对接配置',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `cooperationCompanyList/${typeName}`;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      pageIndex,
      pageSize,
      typeVisible,
      changeType: { status },
    } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList, gardenList, partnerList },
      loading,
    } = this.props;

    const dataSource = dataInfo && dataInfo.list
      ? dataInfo.list.map((item: any) => {
        if (item.type !== 1) {
          item.logisName = item.gardenName;
        }
        return item;
      })
      : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="快递公司" colon={false}>
                  {getFieldDecorator('pcId')(
                    <Select allowClear placeholder="请选择">
                      {partnerList.map((item: any) => {
                        if (item.id !== 3) {
                          return (
                            <Option value={String(item.id)} key={item.id}>
                              <img
                                src={item.img}
                                style={{ width: '18px', height: '18px', marginRight: 8 }}
                                alt=""
                              />
                              {item.name}
                            </Option>
                          );
                        }
                        return false;
                      })}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="校园小区" colon={false}>
                  {getFieldDecorator('gardenId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleAddCooperation}
            >
              添加
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleBatchAddCooperation}
            >
              批量添加
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="提示信息"
          visible={typeVisible}
          onOk={this.handleChangeType}
          onCancel={() => this.handleChangeTypeModal(false)}
        >
          <p>确定要设置当前站点{status === 1 ? '有效' : '无效'}？</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<CooperationListProps>()(CooperationListInfoElem);
